package org.lx.framework.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import lombok.SneakyThrows;
import org.apache.ibatis.reflection.MetaObject;
import org.lx.common.core.domain.model.LoginUser;
import org.lx.common.utils.DateUtils;
import org.lx.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {


    @Autowired
    private HttpServletRequest request;

    @SneakyThrows
    public boolean isExclude() {
        try {
            String requestURI = request.getRequestURI();
            if(requestURI.startsWith("/member")){
                return false;
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        if(!isExclude()) {
            this.strictInsertFill(metaObject, "createBy", String.class, getLoginUserId() + "");
        }

        this.strictInsertFill(metaObject, "createTime", Date.class, DateUtils.getNowDate());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if(!isExclude()) {
            this.setFieldValByName("updateBy", getLoginUserId() + "", metaObject);
        }

        this.setFieldValByName("updateTime", DateUtils.getNowDate(), metaObject);
    }

    /**
     * 获取登录用户id
     *
     * @return 登录用户id
     */
    public Long getLoginUserId() {
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (ObjectUtils.isNotEmpty(loginUser)) {
                return loginUser.getUserId();
            }
            return 1L;
        } catch (Exception e) {
            return 1L;
        }
    }
}
